package sevlet;

import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserDao userDao = new UserDao();
        //记得这一步
        //1.获取参数中的用户名和密码
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //判断是否合法
        if(username == null || password == null) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("输入不合法");
            return;
        }
        //2.查询数据库，看是否有
        User user = userDao.getUserByName(username);
        if(user == null) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户名或者密码输入错误");
            return;
        }
        if(!password.equals(user.getPassword())) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户名或者密码输入错误");
            return;
        }
        //用户名和密码都正确
        //3.创建会话
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);
        //4.重定向
        resp.sendRedirect("blog_list.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        if(session == null) {
            //没有会话，没有登录
            resp.setStatus(403);
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null) {
            //有会话但没有user对象，也是没有登录
            resp.setStatus(403);
            return;
        }
        //两个都存在代表已经登录
        //200 状态码默认会返回，可不写
        resp.setStatus(200);
    }
}
